package com.kayak.emailWorks.util;

//收邮件处理类
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FetchEmail {
	
	protected final static Logger log = LoggerFactory.getLogger(FetchEmail.class);
	public List<Map<String, Object>> getNewEmails(String username,String password) throws IOException {
		List<Map<String, Object>> newMsgList = new ArrayList<Map<String, Object>>(); 
		String protocol = "imap";
		String host = "imap.263.net";
		int port = 143;
		Properties props = new Properties();		
		props.put("mail.imap.host", host);
		props.put("mail.imap.port", port);
		Session session = Session.getDefaultInstance(props);
		Store store = null;
		Folder folder = null;
	try {
		store = session.getStore(protocol);
		store.connect(host,username, password);
		@SuppressWarnings("unused")
		Folder f = store.getDefaultFolder();
		folder = store.getFolder("INBOX");
		folder.open(Folder.READ_WRITE);
		int size = folder.getMessageCount();// 获取收件箱邮件数量
		for (int j = size-20; j <= size; j++) {
			Map<String, Object> s = readAEmail(folder, j);
			if (s == null || s.size() < 1) {
				continue;
			} else {
				newMsgList.add(s);
			}
		}
	} catch (Exception e) {
			e.printStackTrace();
	} finally {
			try {
				if (folder != null) {
					folder.close(false);
				}
				if (store != null) {
					store.close();
				}
			} catch (MessagingException e) {				
				e.printStackTrace();
			}
	}
		return newMsgList;
	}

	public static Map<String, Object> readAEmail(Folder folder, int size)
			throws Exception {
		Map<String, Object> MsgMap = new HashMap<String, Object>();
		Message message = folder.getMessage(size);
		if(message.getFlags().contains(Flags.Flag.SEEN)){
			return null;		//判断邮件是否已读	
		}else{
			StringBuffer bodytext = new StringBuffer();
			message.setFlag(Flags.Flag.SEEN, true);		
			InternetAddress address[] = (InternetAddress[]) message.getFrom();
			String from = address[0].getAddress().toString();
			String subject = message.getSubject();
			String personal = address[0].getPersonal();
			String content = getMailContent(message,bodytext);
			MsgMap.put("from", from);
			MsgMap.put("subject", subject);
			MsgMap.put("personal", personal);
			MsgMap.put("content", content);			
			log.info("======================"+"来自"+from+"的邮件读取完毕"+"==============================");
		}
		return MsgMap;		
		
	}
	
    private static String getMailContent(Part part,StringBuffer bodytext) throws Exception {      
        //判断邮件类型,不同类型操作不同  
        if (part.isMimeType("text/plain")) {      
            bodytext.append((String) part.getContent());      
        } else if (part.isMimeType("text/html")) {      
            bodytext.append(EmailTempletMarket.HtmlToText((String) part.getContent()));      
        } else if (part.isMimeType("multipart/*")) {      
            Multipart multipart = (Multipart) part.getContent();      
            int counts = multipart.getCount();      
            for (int i = 0; i < counts; i++) {      
                getMailContent(multipart.getBodyPart(i),bodytext);      
            }      
        } else if (part.isMimeType("message/rfc822")) {      
            getMailContent((Part) part.getContent(),bodytext);      
        } else {}      
        return bodytext.toString();  
    } 

 
}
